import {
  CONFIG,
  STATUS,
  MAX_INPUT_PER_DATE,
} from "../systems/panyu_jiwei/config.js";
import { commonUtil, adapterUtils } from "../utils/index.js";

export async function input({
  dataList,
  fn,
  fnParams,
  loginFn,
  DICT,
  excelName,
  displayName = "name",
}) {
  try {
    let person;
    let count = 0;
    let loginRes = {};
    loginRes = await loginFn(1);
    for (let i = 0; i < dataList.length; i++) {
      try {
        person = dataList[i];
        if (person.STATUS) continue;
        person = await fn(person, { ...fnParams, ...loginRes });
        if (person?.STATUS === STATUS.FINISH) {
          count++;
        }

        console.log(
          `进度[${i + 1}/${dataList.length}]${`${
            person[displayName] ? `${person[displayName]},` : ""
          }`}[${person.IDNum}],录入结果为[${person.STATUS}]`
        );
        dataList[i] = person;
        await exportResult(excelName, { addSuffix: i === dataList.length - 1 });

        if (count >= MAX_INPUT_PER_DATE) {
          console.log(
            `社区${global.community}账号${global.user.username}在${global.task}任务中录入次数大到设定次数${MAX_INPUT_PER_DATE}`
          );
          loginRes = await loginFn(2);
          count = 0;
        }

        await commonUtil.sleep(Math.random() * CONFIG.SLEEP + CONFIG.MIN_SLEEP);
      } catch (err) {
        person.STATUS = STATUS.WRONG;
        person.NOTE = err;
        dataList[i] = person;
        await exportResult(excelName, { addSuffix: i === dataList.length - 1 });
        console.error(err);
        console.log("执行出错，跳过当前数据，继续录入");
      }
    }
  } catch (err) {
    console.error(err);
    if (err === "登录失败") exit(1);
  }

  async function exportResult(excelName, { addSuffix = false } = {}) {
    let fileName = excelName.split(".")[0];
    if (addSuffix) {
      fileName = `${fileName}-${adapterUtils.formattedDate("", true)}-录入结果`;
    }
    await commonUtil.jsonToExcel({
      data: dataList,
      fileName,
      DICT,
    });

    if (addSuffix) {
      const path = commonUtil.getFilePath({
        backTimes: 3,
        folderPath: "result",
        fileName: excelName,
      });
      await commonUtil.deleteFile(path);
    }
    const path = commonUtil.getFilePath({ backTimes: 3, fileName: excelName });
    await commonUtil.deleteFile(path);
  }
}
